import {Buffer} from "buffer";
import {AxdrSequenceOf} from "../asn1.axdr/AxdrSequenceOf";
import {Data} from "./Data";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {AxdrType} from "../asn1.axdr/AxdrType";


export class SubSeqOfDatas extends AxdrSequenceOf<Data>{

    constructor() {
        super();
    }

    createListElement(): Data {
        return new Data();
    }

    encode(output: ReverseByteArrayOutputStream): number {
        return super.encode(output);
    }

    decode(input: ReverseByteArrayInputStream): number {
        return super.decode(input);
    }

}

export class A_RecordRow implements AxdrType{

    dataCode : Buffer | null = null;
    data : SubSeqOfDatas | null = null;
    length : number = 0;

    constructor() {
    }

    set_length(length : number){
        this.length = length;
    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_data(data : SubSeqOfDatas){
        this.data = data;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;
        this.data = new SubSeqOfDatas();
        this.data.set_length(this.length);
        codeLength += this.data.decode(input);
        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.data != null){
                codeLength = 0;
                codeLength += this.data.encode(output);
            }else{
                throw new Error("data is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess)
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.data != null) {
            return "sequence: {"+ "data: " + this.data  + "}";
        } else {
            return "data is null";
        }
    }

}
